from fastapi import FastAPI
from fastapi import Request
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware

from config import config_cors, config_server
from controller.controller_file import router as file_router
from exception.exception import CustomException
from model.base import Base, engine

"""
启动类，通过 main 方法启动服务
"""

Base.metadata.create_all(bind=engine)

app = FastAPI()

# 跨域解决
if config_cors.CORS_ORIGIN_ENABLE:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=config_cors.ALLOW_ORIGINS,
        allow_credentials=config_cors.ALLOW_CREDENTIALS,
        allow_methods=config_cors.ALLOW_METHODS,
        allow_headers=config_cors.ALLOW_HEADERS
    )

app.include_router(file_router)

# 统一异常处理函数
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )

# 自定义异常处理函数
@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(**config_server.server_config)
